#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Management script."""
import os
from celery import Celery
from flask import request, jsonify


from AmoluoSale.app import create_app
from AmoluoSale.database import db
from AmoluoSale.settings import DevConfig, ProdConfig
from AmoluoSale.item.models import Item

#CONFIG = ProdConfig if os.environ.get('AMOLUOSALE_ENV') == 'prod' else DevConfig
CONFIG = ProdConfig
HERE = os.path.abspath(os.path.dirname(__file__))

def make_celery(app):
    celery = Celery(app.import_name, backend=app.config['CELERY_RESULT_BACKEND'],
                    broker=app.config['BROKER_URL'])
    celery.conf.update(app.config)
    TaskBase = celery.Task
    class ContextTask(TaskBase):
        abstract = True
        def __call__(self, *args, **kwargs):
            with app.app_context():
                return TaskBase.__call__(self, *args, **kwargs)
    celery.Task = ContextTask
    return celery

app = create_app(CONFIG)
celery = make_celery(app)

@celery.task
def holdItem(itemid, quantity):
    item = Item.query.get(itemid)
    item.sold += quantity
    if item.total < item.sold:
        return False
    else: # update db only when it is a vaild order
        db.session.commit()
        release_task = releaseItem.apply_async(args=[itemid, quantity], countdown=5*60)
        # store release_task.id in redis, give it to frontend
        # when order has been successfully created, revoke the task
        return release_task.id

@celery.task
def releaseItem(itemid, quantity):
    item = Item.query.get(itemid)
    item.sold -= quantity
    db.session.commit()

@celery.task
def revokeReleaseTask(task_id):
    celery.control.revoke(task_id)

@celery.task
def checkTaskStatus(task_id):
    return celery.AsyncResult(task_id).state
